package cn.haohaowo;

import cn.haohaowo.entity.Book;
import cn.haohaowo.entity.Order;
import cn.haohaowo.entity.OrderDetail;
import cn.haohaowo.service.OrderDetailService;
import cn.haohaowo.service.OrderService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by luwancai on 18/5/19.
 * DESC:
 */
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;


    @RequestMapping("/queryOrders")
    public String queryOrders(int accountId, int pageNo, int pageSize) {

        JSONArray result = new JSONArray();
        try {
            int minRow = (pageNo - 1) * pageSize;
            List<Order> orderList = orderService.queryOrders(accountId, minRow, pageSize);
            if (null == orderList && !orderList.isEmpty()) {
                result.addAll(orderList);
                return result.toJSONString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    @RequestMapping("/queryOrderById")
    public String queryOrderById(int orderId) {

        JSONObject result = new JSONObject();
        try {
            Order order = orderService.queryOrdersById(orderId);
            if (null == order) {
                return JSONObject.toJSONString(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    @RequestMapping("/saveOrder")
    public String saveOrder(String orderJSON) {

        JSONObject result = new JSONObject();
        try {
            result.put("isSuccess", false);
            if (StringUtils.isEmpty(orderJSON)) {
                return result.toJSONString();
            }

            Order order = JSONObject.parseObject(orderJSON, Order.class);
            orderService.saveOrder(order);
            for (OrderDetail detail : order.getOrderDetailList()) {
                orderDetailService.saveOrderDetail(detail);
            }
            result.put("isSuccess", true);
            return result.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

}
